package com.my.study.net.transfer;

import cn.hutool.core.io.FileUtil;
import com.my.study.io.StreamUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Carlos
 * @version 1.0
 * @Description 文件下载服务端
 *
 * 负责接收客户端发送过来的文件名，并根据文件名查找文件
 * 如果文件存在，返回给客户端，否则返回默认的文件
 *
 * @date 2021/7/4 21:50
 **/
@Slf4j(topic = "c.FileDownloadServer")
public class FileDownloadServer {

    private static final String PATH_PARENT = "D:/file/";


    public static void main(String[] args) throws IOException {

        // 监听9999端口
        ServerSocket serverSocket = new ServerSocket(9999);
        log.debug("等待客户端连接...");
        Socket socket = serverSocket.accept();

        // 读取客户端要下载的文件名
        InputStream is = socket.getInputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        StringBuilder sb = new StringBuilder();
        while ((len = is.read(buf)) != -1) {
            sb.append(new String(buf, 0, len));
        }
        String fileName = sb.toString();
        log.debug("客户端发送的要下载的文件名: {}", fileName);

        if ("system".equals(fileName)) {
            fileName += ".txt";
        } else {
            fileName += "1.txt";
        }

        String filePath = PATH_PARENT + fileName;
        log.debug("filePath: {}", filePath);

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
        byte[] bytes = StreamUtils.streamToByteArray(bis);

        // 写出
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        bos.write(bytes);
        // 之前没有flush，报错"Cannot send after socket shutdown: socket write error"
        bos.flush();
        socket.shutdownOutput();


        // 关闭流
        bos.close();
        bis.close();
        is.close();
        socket.close();
        serverSocket.close();

    }

}
